package com.tax.infrastructure.statemachine;

import com.tax.infrastructure.statemachine.impl.StateMachineException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StateMachineFactory {

    static Map<String/* machineId */,StateMachine> stateMachineMap=new ConcurrentHashMap<>();

    public static  <S,E,C> void register(StateMachine<S,E,C> stateMachine){
        String machineId = stateMachine.getMachineId();
        if (stateMachineMap.get(machineId)!=null){
            throw new StateMachineException("The state machine with id ["+machineId+"] is already built,no need to build again");
        }
        stateMachineMap.put(machineId,stateMachine);
    }

    public <S,E,C> StateMachine<S,E,C> get(String machineId){
        StateMachine stateMachine = stateMachineMap.get(machineId);
        if (null==stateMachine){
            throw new StateMachineException("there is no statemachine instance for "+machineId+", please build it first");
        }
        return stateMachine;
    }
}
